<?php
/**
 * Created by PhpStorm.
 * User: 毛文科
 * Date: 2019-07-28
 * Time: 16:31
 */
namespace app\admin\model;
use think\Db;
use think\Exception;

class MyTable
{
    protected $name = '';
    protected $lang = 255;
    protected $default = '';
    protected $varchar = 'varchar';
    protected $charname = '';
    protected $charnewname = '';
    protected $engine = 'InnoDB';
    protected $tabletype = '单表';
    protected $error = '';

    /**设置表名
     * @param null $name
     * @return $this
     */
    public function setName($name=null){
        if($name){
            $this->name = getTable($name);
        }
        return $this;
    }

    /**设置字段长度
     * @param int $lang
     * @return $this
     */
    public function setLang($lang=255){
        $this->lang = $lang;
        return $this;
    }

    /**设置默认值
     * @param null $default
     */
    public function setDefaults($default=null){
        if($default){
            $this->default = $default;
        }
    }

    /**设置字段类型
     * @param string $varchar
     * @return $this
     */
    public function setCharType($varchar='varchar'){
        if($varchar){
            $this->varchar = $varchar;
        }
        return $this;
    }

    public function setCharName($name=null){
        if($name){
            $this->charname = $name;
        }
        return $this;
    }
    public function setNewChaName($newname=null){
        if($newname){
            $this->charnewname = $newname;
        }
        return $newname;
    }

    /**设置表引擎
     * @param string $engine
     * @return $this
     */
    public function setEngine($engine='InnoDB'){
        if($engine){
            $this->engine = $engine;
        }
        return $this;
    }

    /**设置表类型
     * @param string $type
     * @return $this
     */
    public function setTableType($type='单表'){
        if($type){
            $this->tabletype = $type;
        }
        return $this;
    }

    /**添加表
     * @return bool
     */
    public function addTable(){
        $table = config('database.prefix').$this->name;
        if($this->tabletype=='单表'){
            $sql ="CREATE TABLE $table (id int(255) auto_increment primary key,`name` varchar(255) default '',`dir` varchar(255) default '',`cid` int(255) default null,`sort` int(255) default 100,`create_time` int(255) default 0,`update_time` int(255) default 0,`status` int(1) default '1',delete_time int(50) default null,`delete` int(1) default 1";
        }else{
            $sql = "create table $table (id int(255) auto_increment primary key,name varchar(255) default '',pid int(255) default 0,sort int(255) default 100,tubiao varchar(255) default '',create_time int(255) default 0,`delete` int(1) default 0,status int(1) default 1,delete_time int(50) default null";
        }
        $sql = $sql.")engine=$this->engine";
        try{
            Db::execute($sql);
            return true;
        }catch (\ErrorException $e){
            return false;
        }
    }

    /**添加表字段
     * @param $model_id
     * @return bool
     */
    public function addMyFie($model_id){
        if($this->tabletype=='单表'){
            $array = config('danbiao.');
        }else{
            $array = config('lianbiao.');
        }
        foreach ($array as $value){
            $value['model_id'] = $model_id;
            Db::name(getTable('fields'))
                ->insert($value);
        }
        return true;
    }
    public function addMyModel($data){
        $data['table'] = getTable($data['table']);
        $id = Db::name(getTable('models'))
            ->insertGetId($data,true);
        return $id;
    }
    public static function addAllTable($data){
        $obj = new MyTable();
        $obj->setName($data['table']);
        $arr = Db::name(getTable('models'))
            ->where('table',getTable($data['table']))
            ->find();
        if($arr){
            return false;
        }
        $obj->setTableType($data['type']);
        $obj->setEngine($data['engine']);
        if($obj->addTable()){
            $model_id = $obj->addMyModel($data);
            if($obj->addMyFie($model_id)){
                if($data['type']=='联表'){
                    $array = ['增','删','改','查'];
                    foreach ($array as $value){
                        Db::name(getTable('jurs'))
                            ->insert([
                               'name'=>$data['name'],
                                'model_id'=>$model_id,
                                'descs'=>$value,
                                'status'=>1,
                                'create_time'=>time()
                            ]);
                    }
                    MyAuth::add();
                }
                $obj->getFiles(session('modular')."_".$data['table']);
                return true;
            }else{
                return false;
            }
        }else{
            return false;
        }
    }

    /**添加模型
     * @param $name
     */
    public function getFiles($name){
        $modelname = $name;
        $name = explode('_',$name);
        $str = '';
        foreach ($name as $key=>$value){
            if($key!==0){
                $str .= ucwords($value);
            }
        }
        $url = '../application/'.session('modular').'/model';
        if(!is_dir($url)){
            chmod('../application',0777);
            mkdir($url,0777,true);
        }
        $newstr = '<?php
/**
 * Created by PhpStorm.
 * User: 毛文科
 * Date: 2019/5/24
 * Time: 10:49
 */
namespace app\\'.session('modular').'\\model;
use think\Model;
use think\model\concern\SoftDelete;

class '.$str.' extends Model
{
    protected $name = "'.$modelname.'";
    protected $pk = "id";
    use SoftDelete;
    protected $deleteTime = "delete_time";
}';
        chmod($url,0777);
        file_put_contents($url.'/'.$str.'.php',$newstr);
    }

    /**修改表引擎
     * @param $table
     * @param $newengine
     * @return bool
     */
    static public function changeEngine($table,$newengine){
        $table = config('database.prefix').$table;
        $sql = "ALTER TABLE $table engine=$newengine";
        try{
            Db::execute($sql);
        }catch (Exception $e){
            return false;
        }
        return true;
    }

    /**删除表
     * @param $table
     * @return bool
     */
    static public function delTable($table){
        $table = config('database.prefix').$table;
        $sql = "DROP TABLE $table";
        try{
            Db::execute($sql);
        }catch (Exception $e){
            return false;
        }
        return true;
    }
    static public function delId($id){
        $array = Db::name(session('modular').'_models')
            ->where('id','in',$id)
            ->select();
        foreach ($array as $valie){
            MyTable::delteFile($valie['table']);
        }
        return true;
    }
    static public function delteFile($name){
        $name = explode('_',$name);
        $str = '';
        foreach ($name as $key=>$value){
            if($key>0){
                $str.=ucwords($value);
            }
        }
        if(is_file('../application/'.session('modular').'/model/'.$str.'.php')){
            chmod('../application/'.session('modular').'/model/'.$str.'.php',0777);
            unlink('../application/'.session('modular').'/model/'.$str.'.php');
        }
    }

    /**添加字段
     * @return bool
     */
    public function addField($table){
        $table = config('database.prefix').$table;
        $charname = $this->charname;
        $varchar = $this->varchar;
        $lang = $this->lang;
        $default = $this->default;
        if($varchar=='text'){
            $lang = 0;
        }
        if($varchar=='int'){
            if(!$default){
                $default = 0;
            }
        }
        if($varchar=='float'){
            $jindu = config('newapp.float');
            if($default||$default==0){
                $sql = "alter table $table add $charname $varchar($lang,$jindu) default $default";
            }else{
                $sql = "alter table $table add $charname $varchar($lang,$jindu)";
            }
        }else{
            if($varchar=='int'){
                if($default||$default==0){
                    $sql = "alter table $table add $charname $varchar($lang) default $default";
                }else{
                    $sql = "alter table $table add $charname $varchar($lang)";
                }
            }else{
                if($default){
                    $sql = "alter table $table add $charname $varchar($lang) default $default";
                }else{
                    $sql = "alter table $table add $charname $varchar($lang)";
                }
            }
        }
//        echo $sql;exit;
        try{
            Db::execute($sql);
        }catch (Exception $e){
            return false;
        }
        return true;
    }
    public static function addFields($data=[]){
        $obj = new MyTable();
        $subject = new MySubject();
        $subject->setModelId($data['model_id']);
        $table = $subject->getModel('table');
//        $obj->setName($table);
        if($data['field']??null){
            $obj->setCharName($data['field']);
        }else{
            return false;
        }
        if($data['type']??null){
            $obj->setCharType($data['type']);
        }else{
            return false;
        }
        if($data['lang']??null){
            if($data['type']=='text'){
                $obj->setLang(0);
            }else{
                $obj->setLang($data['lang']);
            }
        }
        if($data['defaults']??null){
            $obj->setDefaults($data['defaults']);
        }
        $bool = $obj->addField($table);
        if($bool){
            return Db::name(getTable('fields'))
                ->insert($data,true);
        }else{
            return false;
        }
    }
//    public static function delField($table,$field){
//        return 'haha';
//        $table = config('database.prefix').$table;
//        return $table;
//        $sql = "ALTER TABLE $table  DROP $field";
//        return $sql;
//        try{
//            Db::execute($sql);
//        }catch (Exception $e){
//            return false;
//        }
//        return true;
//    }
    public function chanField($table,$data=[]){
        $table = config('database.prefix').$table;
        $charname = $this->charname;
        $charnewname = $this->charnewname;
        $varchar = $this->varchar;
        $lang = $this->lang;
        $default = $this->default;
        if($varchar=='text'){
            $lang = 0;
        }
        if($varchar=='int'){
            if(!$default){
                $default = 0;
            }
        }
        if($charname==$charnewname&&$varchar==$data['type']&&$lang==$data['lang']&&$default==$data['defaults']){
            return true;
        }
        if($varchar=='float'){
            $jindu = config('newapp.float');
            if($default){
                if($charname==$charnewname){
                    $sql = "alter table $table MODIFY $charnewname $varchar($lang,$jindu) default '$default'";
                }else{
                    $sql = "alter table $table CHANGE $charname $charnewname $varchar($lang,$jindu) default '$default'";
                }
            }else{
                if($charname==$charnewname){
                    $sql = "alter table $table MODIFY $charnewname $varchar($lang,$jindu)";
                }else{
                    $sql = "alter table $table CHANGE $charname $charnewname $varchar($lang,$jindu)";
                }
            }
        }else{
            if($default){
                if($charname==$charnewname){
                    $sql = "alter table $table MODIFY $charnewname $varchar($lang) default '$default'";
                }else{
                    $sql = "alter table $table CHANGE $charname $charnewname $varchar($lang) default '$default'";
                }
            }else{
                if($charname==$charnewname){
                    $sql = "alter table $table MODIFY $charnewname $varchar($lang)";
                }else{
                    $sql = "alter table $table CHANGE $charname $charnewname $varchar($lang)";
                }
            }
        }
//        return $sql;
        try{
            Db::execute($sql);
        }catch (Exception $e){
            return false;
        }
        return true;
    }
    public static function delField($table=null,$field=null){
        $table = config('database.prefix').$table;
        $sql = "ALTER TABLE $table  DROP $field";
        try{
            Db::execute($sql);
        }catch (Exception $e){
            return false;
        }
        return true;
    }
}